// 创建用户相关的小仓库
import { defineStore } from "pinia";
import { LoginApi, UserInfoApi, reqLogout } from '@/api/user';
import { loginForm, LoginInfoResponseData, userResponseData } from "@/api/user/type"
import cloneDeep from "lodash/cloneDeep";
import type { UserState } from "./types/type";
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from "@/utils/token"
import { routerData, asyncRouter, anyRouter } from "@/router/router.ts"
import router from "../../../router";

//用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asnycRoute: any, routes: any) {
  return asnycRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterAsyncRoute(item.children, routes)
      }
      return true
    }
  })
}
// 创建用户小仓库
const useUserStore = defineStore("user", {
  state: (): UserState => {
    return {
      token: localStorage.getItem("token") || GET_TOKEN(),
      menuRoutes: routerData, //仓库存储
      username: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
      avatar: 'https://img.zcool.cn/community/01a3865ab91314a8012062e3c38ff6.png@1280w_1l_2o_100sh.png'
    }
  },
  actions: {
    async userLogin(data: loginForm) {
      const result: userResponseData = await LoginApi(data);
      console.log('登录');
      // 200进入返回resolve       非200进入reject.
      if (result.code === 200) {
        this.token = result.data;
        console.log(result);

        SET_TOKEN(this.token)
        return Promise.resolve()
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },
    async requestUserInfo() {
      console.log("执行用户info");
      // 获得用户api。 
      const userInfo: LoginInfoResponseData = await UserInfoApi()
      this.buttons = userInfo.data.buttons
      console.log(userInfo);
      const userAsyncRouter = filterAsyncRoute(cloneDeep(asyncRouter), userInfo.data.routes)
      console.log(this.userAsyncRouter);

      this.menuRoutes = [...userAsyncRouter, ...routerData, anyRouter];
      [...userAsyncRouter, anyRouter].forEach(item => {

        router.addRoute(item)

      })


      console.log(this.menuRoutes);
      if (userInfo.code != 200) return Promise.reject(new Error(userInfo.message))
      const { name, avatar } = userInfo.data
      this.username = name
      this.avatar = avatar
      return Promise.resolve()
    },
    logout() {
      reqLogout(this.token)
      this.token = ''
      this.username = ''
      this.avatar = ''
      REMOVE_TOKEN()
    }
  },
  getters: {


  }
})
// 暴露获得用户仓库的方法。
export default useUserStore

